<template>
  <div class="training-page">
    <el-card>
      <el-form :inline="true" :model="searchForm"
        class="search-form-container mb-6 bg-gray-50 p-4 rounded-lg shadow-sm">
        <div class="search-inputs-actions">
          <div class="flex items-center flex-wrap gap-x-4 gap-y-2">
            <el-form-item label="" class="mb-0">
              <el-input v-model="searchForm.name" placeholder="实训名称" style="width: 150px;" clearable />
            </el-form-item>
            <el-form-item label="" class="mb-0">
              <el-input v-model="searchForm.course" placeholder="课程" style="width: 120px;" clearable />
            </el-form-item>
            <el-form-item label="" class="mb-0">
              <el-select v-model="searchForm.type" placeholder="类型" style="width: 100px;" clearable>
                <el-option label="线上" value="线上" />
                <el-option label="线下" value="线下" />
              </el-select>
            </el-form-item>
            <el-form-item label="" class="mb-0">
              <el-select v-model="searchForm.status" placeholder="状态" style="width: 110px;" clearable>
                <el-option label="进行中" value="进行中" />
                <el-option label="已结束" value="已结束" />
                <el-option label="即将开始" value="即将开始" />
              </el-select>
            </el-form-item>
            <el-form-item label="" class="mb-0">
              <el-input v-model="searchForm.manager" placeholder="负责人" style="width: 100px;" clearable />
            </el-form-item>
            <el-form-item class="mb-0">
              <el-button @click="handleSearch" class="gradient-purple-blue-button">查询</el-button>
              <el-button @click="resetSearch" class="gradient-blue-cyan-button" style="margin-left: 8px;">重置</el-button>
            </el-form-item>
          </div>

          <div class="flex items-center gap-x-4">
            <el-button @click="openAddDialog" class="gradient-blue-toggle-button">新增实训</el-button>
            <el-button @click="toggleView" class="gradient-blue-toggle-button">
              {{ isCardView ? '切换为列表' : '切换为卡片' }}
            </el-button>
          </div>
        </div>
      </el-form>

      <el-row :gutter="20" class="chart-section">
        <el-col :span="8">
          <el-card>
            <h3>课程类型分布</h3>
            <div ref="courseTypeChart" style="width: 100%; height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card>
            <h3>各课程报名人数分布</h3>
            <div ref="registrationsChart" style="width: 100%; height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card>
            <h3>项目进度概览</h3>
            <div class="project-progress-list">
              <h4>即将开始</h4>
              <ul v-if="projectProgress.即将开始.length">
                <li v-for="item in projectProgress.即将开始" :key="item.id">{{ item.name }}</li>
              </ul>
              <p v-else>暂无即将开始的项目</p>

              <h4>进行中</h4>
              <ul v-if="projectProgress.进行中.length">
                <li v-for="item in projectProgress.进行中" :key="item.id">{{ item.name }}</li>
              </ul>
              <p v-else>暂无进行中的项目</p>

              <h4>已结束</h4>
              <ul v-if="projectProgress.已结束.length">
                <li v-for="item in projectProgress.已结束" :key="item.id">{{ item.name }}</li>
              </ul>
              <p v-else>暂无已结束的项目</p>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <div v-loading="loading">
        <template v-if="isCardView">
          <el-row :gutter="20" class="training-card-grid">
            <template v-if="trainingList.length > 0">
              <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in trainingList" :key="item.id">
                <el-card class="training-card">
                  <div class="training-card-content">
                    <h4 class="training-card-title" :title="item.name">{{ item.name }}</h4>
                    <p class="training-card-info"><span class="info-label">课程:</span> {{ item.course }}</p>
                    <p class="training-card-info"><span class="info-label">类型:</span> {{ item.type }}</p>
                    <p class="training-card-info"><span class="info-label">状态:</span> {{ item.status }}</p>
                    <p class="training-card-info"><span class="info-label">开始:</span> {{ dateFormatter(item, null,
                      item.start) }}</p>
                    <p class="training-card-info"><span class="info-label">结束:</span> {{ dateFormatter(item, null,
                      item.end) }}</p>
                    <p class="training-card-info"><span class="info-label">报名人数:</span> {{ item.registrations }}
                    </p>
                    <p class="training-card-info"><span class="info-label">负责人:</span> {{ item.manager }}</p>
                  </div>
                  <div class="training-card-actions">
                    <el-button size="mini" @click="openEditDialog(item)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="openDeleteDialog(item)"
                      class="light-red-button">删除</el-button>
                  </div>
                </el-card>
              </el-col>
            </template>
            <div v-else class="empty-trainings">
              <el-empty description="暂无实训，请新增或调整搜索条件"></el-empty>
            </div>
          </el-row>
        </template>

        <template v-else>
          <el-table :data="trainingList" border style="width: 100%; margin-top: 20px;">
            <el-table-column prop="name" label="项目名称" />
            <el-table-column prop="course" label="课程" />
            <el-table-column prop="type" label="类型" />
            <el-table-column prop="status" label="状态" />
            <el-table-column prop="start" label="开始" :formatter="dateFormatter" />
            <el-table-column prop="end" label="结束" :formatter="dateFormatter" />
            <el-table-column prop="registrations" label="报名人数" />
            <el-table-column prop="manager" label="负责人" />
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="openDeleteDialog(scope.row)"
                  class="light-red-button">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
    </el-card>

    <el-dialog :title="editMode ? '编辑实训' : '新增实训'" v-model="showDialog">
      <el-form :model="form" label-width="80px">
        <el-form-item label="项目名称"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="课程"><el-input v-model="form.course" /></el-form-item>
        <el-form-item label="类型">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option label="线上" value="线上" />
            <el-option label="线下" value="线下" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="进行中" value="进行中" />
            <el-option label="已结束" value="已结束" />
            <el-option label="即将开始" value="即将开始" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始">
          <el-date-picker v-model="form.start" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
            placeholder="选择开始时间" />
        </el-form-item>
        <el-form-item label="结束">
          <el-date-picker v-model="form.end" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
            placeholder="选择结束时间" />
        </el-form-item>
        <el-form-item label="报名人数"><el-input-number v-model="form.registrations" :min="0" /></el-form-item>
        <el-form-item label="负责人"><el-input v-model="form.manager" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="确认删除" v-model="showDeleteDialog" width="300px">
      <div>确定要删除该实训记录吗？</div>
      <template #footer>
        <el-button @click="showDeleteDialog = false">取消</el-button>
        <el-button type="danger" @click="deleteRecord" class="light-red-button">删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import {
  addTrainingRecord,
  updateTrainingRecord,
  deleteTrainingRecord,
  // searchByName, // These specific search functions are no longer directly used in handleSearch
  // searchByCourse,
  // searchByType,
  // searchByStatus,
  // searchByManager,
  getAllTraining
} from '@/services/trainingService';
import { ElMessage } from 'element-plus';

const trainingList = ref([]);
const showDialog = ref(false);
const showDeleteDialog = ref(false);
const editMode = ref(false);
const form = reactive({
  id: null,
  name: '',
  course: '',
  type: '',
  status: '',
  start: '',
  end: '',
  registrations: 0,
  manager: ''
});
const currentDeleteId = ref(null);
const searchForm = reactive({ name: '', course: '', type: '', status: '', manager: '' });

// State for view toggle, default to card view
const isCardView = ref(true);

// ECharts 相关
const courseTypeChart = ref(null);
const registrationsChart = ref(null);
let myCourseTypeChart = null;
let myRegistrationsChart = null;

// 项目进度数据
const projectProgress = reactive({
  '即将开始': [],
  '进行中': [],
  '已结束': []
});

async function loadList() {
  trainingList.value = await getAllTraining();
  updateChartsAndProgress();
}

async function handleSearch() {
  let resultList = [];
  // Build a list of active filters
  const activeFilters = Object.keys(searchForm).filter(key => searchForm[key]);

  // If no filters are active, load all training records
  if (activeFilters.length === 0) {
    resultList = await getAllTraining();
  } else {
    // Apply filters sequentially
    let filteredList = await getAllTraining(); // Start with all data for filtering
    if (searchForm.name) {
      filteredList = filteredList.filter(item => item.name.includes(searchForm.name));
    }
    if (searchForm.course) {
      filteredList = filteredList.filter(item => item.course.includes(searchForm.course));
    }
    if (searchForm.type) {
      filteredList = filteredList.filter(item => item.type === searchForm.type);
    }
    if (searchForm.status) {
      filteredList = filteredList.filter(item => item.status === searchForm.status);
    }
    if (searchForm.manager) {
      filteredList = filteredList.filter(item => item.manager.includes(searchForm.manager));
    }
    resultList = filteredList;
  }

  trainingList.value = resultList;
  updateChartsAndProgress();
}


function resetSearch() {
  Object.assign(searchForm, { name: '', course: '', type: '', status: '', manager: '' });
  loadList();
}

// Toggle view function
const toggleView = () => {
  isCardView.value = !isCardView.value;
};


function openAddDialog() {
  editMode.value = false;
  Object.assign(form, { id: null, name: '', course: '', type: '', status: '', start: '', end: '', registrations: 0, manager: '' });
  showDialog.value = true;
}

function openEditDialog(row) {
  editMode.value = true;
  // Ensure dates are correctly formatted for the picker if they come as strings
  const startDate = row.start ? new Date(row.start).toISOString() : '';
  const endDate = row.end ? new Date(row.end).toISOString() : '';

  Object.assign(form, { ...row, start: startDate, end: endDate });
  showDialog.value = true;
}

function openDeleteDialog(row) {
  currentDeleteId.value = row.id;
  showDeleteDialog.value = true;
}

async function submitForm() {
  if (!form.name || !form.course || !form.type || !form.status || !form.start || !form.end || !form.manager) {
    ElMessage.error('请填写完整信息');
    return;
  }

  // Convert dates back to a consistent format if necessary before sending to service
  const submissionForm = { ...form };
  if (submissionForm.start) {
    submissionForm.start = new Date(submissionForm.start).getTime(); // Convert to timestamp
  }
  if (submissionForm.end) {
    submissionForm.end = new Date(submissionForm.end).getTime(); // Convert to timestamp
  }

  if (editMode.value) {
    const res = await updateTrainingRecord(submissionForm);
    if (res.success) {
      ElMessage.success(res.message);
      showDialog.value = false;
      await loadList();
    } else {
      ElMessage.error(res.message);
    }
  } else {
    const res = await addTrainingRecord(submissionForm);
    if (res.success) {
      ElMessage.success(res.message);
      showDialog.value = false;
      await loadList();
    } else {
      ElMessage.error(res.message);
    }
  }
}

async function deleteRecord() {
  const res = await deleteTrainingRecord(currentDeleteId.value);
  if (res.success) {
    ElMessage.success(res.message);
    showDeleteDialog.value = false;
    await loadList();
  } else {
    ElMessage.error(res.message);
  }
}

// 日期格式化函数，支持时间戳、字符串、Date
function dateFormatter(row, column, cellValue) {
  if (!cellValue) return '';
  let dateObj;
  if (typeof cellValue === 'number') {
    dateObj = new Date(cellValue);
  } else if (typeof cellValue === 'string' && /^\d+$/.test(cellValue)) {
    dateObj = new Date(Number(cellValue));
  } else if (typeof cellValue === 'string') {
    dateObj = new Date(cellValue);
  } else if (cellValue instanceof Date) {
    dateObj = cellValue;
  } else {
    return cellValue;
  }
  if (isNaN(dateObj.getTime())) return cellValue;
  const y = dateObj.getFullYear();
  const m = String(dateObj.getMonth() + 1).padStart(2, '0');
  const d = String(dateObj.getDate()).padStart(2, '0');
  const hh = String(dateObj.getHours()).padStart(2, '0');
  const mm = String(dateObj.getMinutes()).padStart(2, '0');
  return `${y}-${m}-${d} ${hh}:${mm}`;
}

// 计算图表数据和项目进度数据
function calculateChartData() {
  const courseTypeCounts = { '线上': 0, '线下': 0 };
  const registrationsByCourse = {};
  const progressData = {
    '即将开始': [],
    '进行中': [],
    '已结束': []
  };

  trainingList.value.forEach(item => {
    // 课程类型饼状图数据
    if (item.type in courseTypeCounts) {
      courseTypeCounts[item.type]++;
    }

    // 各课程报名人数分布饼状图数据
    if (registrationsByCourse[item.course]) {
      registrationsByCourse[item.course] += item.registrations;
    } else {
      registrationsByCourse[item.course] = item.registrations;
    }

    // 项目进度数据
    if (item.status in progressData) {
      progressData[item.status].push({ id: item.id, name: item.name });
    }
  });

  // 格式化课程类型饼状图数据
  const courseTypeChartData = Object.entries(courseTypeCounts).map(([name, value]) => ({ name, value }));

  // 格式化报名人数饼状图数据
  const registrationsChartData = Object.entries(registrationsByCourse).map(([name, value]) => ({ name, value }));

  return { courseTypeChartData, registrationsChartData, progressData };
}

// 渲染图表
function renderCharts(courseTypeData, registrationsData) {
  // Dispose existing charts to prevent memory leaks and re-render issues
  if (myCourseTypeChart) {
    myCourseTypeChart.dispose();
  }
  if (myRegistrationsChart) {
    myRegistrationsChart.dispose();
  }

  // Initialize and render Course Type Pie Chart
  if (courseTypeChart.value) {
    myCourseTypeChart = echarts.init(courseTypeChart.value);
    myCourseTypeChart.setOption({
      tooltip: { trigger: 'item' },
      legend: { orient: 'vertical', left: 'left' },
      series: [
        {
          name: '课程类型',
          type: 'pie',
          radius: '50%',
          data: courseTypeData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    });
  }

  // Initialize and render Registrations By Course Pie Chart
  if (registrationsChart.value) {
    myRegistrationsChart = echarts.init(registrationsChart.value);
    myRegistrationsChart.setOption({
      tooltip: { trigger: 'item' },
      series: [
        {
          name: '报名人数',
          type: 'pie',
          radius: '50%',
          data: registrationsData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    });
  }
}

// 更新图表和项目进度列表
function updateChartsAndProgress() {
  const { courseTypeChartData, registrationsChartData, progressData } = calculateChartData();
  renderCharts(courseTypeChartData, registrationsChartData);
  Object.assign(projectProgress, progressData);
}

// 监听 trainingList 变化，重新渲染图表和更新项目进度
watch(trainingList, () => {
  updateChartsAndProgress();
}, { deep: true });


onMounted(async () => {
  await loadList(); // Ensure data is loaded before charts are initialized
  window.addEventListener('resize', () => {
    myCourseTypeChart && myCourseTypeChart.resize();
    myRegistrationsChart && myRegistrationsChart.resize();
  });
});

</script>

<style scoped>
.training-page {
  padding: 32px 24px;
  background: #f8f9fb;
}

.mb-6 {
  margin-bottom: 1.5rem;
  /* 24px */
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.flex-wrap {
  flex-wrap: wrap;
}

/* Flex gap for items within the search bar */
.gap-x-4 {
  column-gap: 1rem;
  /* 16px */
}

.gap-y-2 {
  row-gap: 0.5rem;
  /* 8px */
}

/* Container for the search inputs and action buttons (new structure) */
.search-inputs-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
  gap: 10px; /* Overall gap between search input group and action button group */
}


/* Search form container styling */
.search-form-container {
  background-color: #f9fafb;
  padding: 1rem;
  border-radius: 0.5rem;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 1.5rem;
}

/* El-form-item specific overrides to remove default bottom margin for inline forms */
.el-form-item.mb-0 {
  margin-bottom: 0 !important;
}


.chart-section {
  margin-top: 20px;
}

.project-progress-list {
  height: 300px;
  overflow-y: auto;
  padding-right: 10px;
}

.project-progress-list ul {
  list-style: none;
  padding-left: 0;
  margin-top: 8px;
}

.project-progress-list li {
  margin-bottom: 4px;
  color: #606266;
}

.project-progress-list h4 {
  margin-top: 15px;
  margin-bottom: 5px;
  color: #303133;
}

/* --- Custom Button Styles (Gradient and Lighter) --- */

/* 查询按钮: 紫色到蓝色的渐变 */
.gradient-purple-blue-button {
  color: #fff !important;
  background-image: linear-gradient(to right, #8b5dbd, #548ee0) !important;
  /* 紫色到蓝色渐变 */
  border-color: #8b5dbd !important;
  /* 初始边框颜色 */
  transition: all 0.3s ease;
}

.gradient-purple-blue-button:hover,
.gradient-purple-blue-button:focus {
  background-image: linear-gradient(to right, #9d70d1, #69a7f3) !important;
  /* 悬停时渐变颜色稍亮 */
  border-color: #9d70d1 !important;
  opacity: 0.9;
  transform: translateY(-2px);
  /* 添加上浮效果 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  /* 添加阴影效果 */
}

.gradient-purple-blue-button:active {
  background-image: linear-gradient(to right, #7b51aa, #4a7cc9) !important;
  /* 点击时渐变颜色稍深 */
  border-color: #7b51aa !important;
  transform: translateY(0);
  /* 点击时回到原位 */
  box-shadow: none;
  /* 点击时移除阴影 */
}

/* 重置按钮: 蓝色到青色的渐变 */
.gradient-blue-cyan-button {
  color: #fff !important;
  background-image: linear-gradient(to right, #548ee0, #38afb5) !important;
  /* 蓝色到青色渐变 */
  border-color: #548ee0 !important;
  /* 初始边框颜色 */
  transition: all 0.3s ease;
}

.gradient-blue-cyan-button:hover,
.gradient-blue-cyan-button:focus {
  background-image: linear-gradient(to right, #69a7f3, #4fd3d8) !important;
  /* 悬停时渐变颜色稍亮 */
  border-color: #69a7f3 !important;
  opacity: 0.9;
  transform: translateY(-2px);
  /* 添加上浮效果 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  /* 添加阴影效果 */
}

.gradient-blue-cyan-button:active {
  background-image: linear-gradient(to right, #4a7cc9, #2f969b) !important;
  /* 点击时渐变颜色稍深 */
  border-color: #4a7cc9 !important;
  transform: translateY(0);
  /* 点击时回到原位 */
  box-shadow: none;
  /* 点击时移除阴影 */
}

/* Toggle/Add button: A distinct blue-ish gradient for the toggle button */
.gradient-blue-toggle-button {
  color: #fff !important;
  background-image: linear-gradient(to right, #3f51b5, #2196f3) !important;
  /* Indigo to Blue */
  border-color: #3f51b5 !important;
  transition: all 0.3s ease;
}

.gradient-blue-toggle-button:hover,
.gradient-blue-toggle-button:focus {
  background-image: linear-gradient(to right, #5c6bc0, #42a5f5) !important;
  /* Lighter shades on hover */
  border-color: #5c6bc0 !important;
  opacity: 0.9;
  transform: translateY(-2px);
  /* 添加上浮效果 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  /* 添加阴影效果 */
}

.gradient-blue-toggle-button:active {
  background-image: linear-gradient(to right, #303f9f, #1976d2) !important;
  /* Darker shades on active */
  border-color: #303f9f !important;
  transform: translateY(0);
  /* 点击时回到原位 */
  box-shadow: none;
  /* 点击时移除阴影 */
}


/* Custom light red button style */
.light-red-button {
  background-color: #FEE2E2 !important;
  /* Light red background */
  color: #EF4444 !important;
  /* Slightly darker red text */
  border-color: #FEE2E2 !important;
  /* Light red border */
}

.light-red-button:hover,
.light-red-button:focus {
  background-color: #FECDCD !important;
  /* Slightly darker light red on hover */
  border-color: #FECDCD !important;
}

.light-red-button:active {
  background-color: #FBB0B0 !important;
  /* Even darker light red on active */
  border-color: #FBB0B0 !important;
}

/* Training Card View Styles (adapted from CourseManagement) */
.training-card-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 20px;
  padding-bottom: 20px;
  justify-content: space-around;
}

.training-card {
  min-height: 280px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.2s ease;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-color: #ffffff;
  border: 1px solid #e9e9e9;
}

.training-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.training-card-content {
  padding: 15px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.training-card-title {
  font-size: 1.1em;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
  white-space: normal;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
  height: 2.8em;
}

.training-card-info {
  font-size: 0.9em;
  color: #666;
  margin-bottom: 0;
  line-height: 1.4;
}

.training-card-info .info-label {
  font-weight: 500;
  color: #444;
  margin-right: 5px;
}

.training-card-actions {
  padding: 10px 15px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  background-color: #fafafa;
}

.training-card-actions .el-button {
  min-width: unset;
  padding: 7px 12px;
  font-size: 0.85em;
}

.empty-trainings {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}
</style>